package com.sunwayworld.basemodule.rm.equipment.equiptfileacq.support;

import com.hierynomus.smbj.session.Session;
import com.sunwayworld.baseline.framework.utils.SmbV1Utils;
import com.sunwayworld.baseline.framework.utils.SmbV23Utils;
import com.sunwayworld.basemodule.rm.equipment.equiptfileacq.bean.LimsEquiptFileAcqBean;
import com.sunwayworld.basemodule.rm.equipment.equiptfileacq.bean.LimsEquiptFileAcqConfigBean;
import com.sunwayworld.basemodule.rm.equipment.equiptfileacq.exector.FileAcqExector;
import com.sunwayworld.basemodule.rm.equipment.equiptfileacq.service.LimsEquiptFileAcqService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.utils.FtpUtils;
import jcifs.smb.SmbFile;
import org.apache.commons.net.ftp.FTPClient;

import java.util.ArrayList;
import java.util.List;

public class EquiptAcqEntity {

    private LimsEquiptFileAcqConfigBean equiptFileAcqConfigBean;
    private FileAcqExector exector;

    private EquiptAcqEntity(){}

    public EquiptAcqEntity(LimsEquiptFileAcqConfigBean equiptFileAcqConfigBean){
        this.equiptFileAcqConfigBean = equiptFileAcqConfigBean;
        String exectorName = equiptFileAcqConfigBean.getExectorName();
        exector = ApplicationContextHelper.getApplicationContext().getBean(exectorName, FileAcqExector.class);
    }

    public List<LimsEquiptFileAcqBean> acqFiles(){
        String mode = equiptFileAcqConfigBean.getAcqMode();
        String ip = equiptFileAcqConfigBean.getIp();
        String port = equiptFileAcqConfigBean.getPort();
        String username = equiptFileAcqConfigBean.getUsername();
        String password = equiptFileAcqConfigBean.getPassword();
        List<LimsEquiptFileAcqBean> equiptFileAcqBeanList = new ArrayList<>();
        if ("ftp".equals(mode)){
            FTPClient ftpClient = FtpUtils.getFtpClient(ip, Integer.parseInt(port), username, password);
            equiptFileAcqBeanList = exector.acqFileFromFtp(ftpClient, equiptFileAcqConfigBean);
        }else if("shareDocV1".equals(mode)){
            SmbFile smbFile = SmbV1Utils.getSmbFile(ip, port, username, password);
            equiptFileAcqBeanList = exector.acqFileFromShareDocV1(smbFile, equiptFileAcqConfigBean);
        }else if("shareDocV23".equals(mode)){
            Session sesison = SmbV23Utils.getSession(ip, username, password);
            equiptFileAcqBeanList = exector.acqFileFromShareDocV23(sesison, equiptFileAcqConfigBean);
        }
        LimsEquiptFileAcqService limsEquiptFileAcqService = ApplicationContextHelper.getBean(LimsEquiptFileAcqService.class);
        limsEquiptFileAcqService.getDao().insert(equiptFileAcqBeanList);
        return equiptFileAcqBeanList;
    }

    public void analysisFiles(List<LimsEquiptFileAcqBean> equiptFileAcqBeans){
        exector.analysisFiles(equiptFileAcqBeans);
    }
}
